package com.zhejiangzhengyuan.municipal_common.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhejiangzhengyuan.municipal_common.entity.*;
import com.zhejiangzhengyuan.municipal_common.entity.dto.JurisdictionDto;
import com.zhejiangzhengyuan.municipal_common.entity.vo.ActionTitle;
import com.zhejiangzhengyuan.municipal_common.entity.vo.ActionVo;
import com.zhejiangzhengyuan.municipal_common.entity.vo.JurisdictionVo;
import com.zhejiangzhengyuan.municipal_common.mapper.*;
import com.zhejiangzhengyuan.municipal_common.response.ResponseVo;
import com.zhejiangzhengyuan.municipal_common.service.ActionService;
import com.zhejiangzhengyuan.municipal_common.utils.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.zhejiangzhengyuan.municipal_common.utils.DateFormatUtil.timeFormat;

/**
 * <p>
 * 服务API--行为表，提供两种权限比对方式：1、基于权限点；2、基于URL 服务实现类
 * </p>
 *
 * @author linju
 * @since 2019-11-22
 */
@Service
@Slf4j
public class ActionServiceImpl extends ServiceImpl<ActionMapper, Action> implements ActionService {
    @Autowired
    private ActionMapper actionMapper;
    @Autowired
    private SubjectMapper subjectMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private PermissionActionMappingMapper permissionActionMappingMapper;
    @Autowired
    private RolePermissionMappingMapper rolePermissionMappingMapper;

    @Override
    public List<Action> findBySubjectIdByUrlAction(Long id, String url) {
        List<Action> actionResult = actionMapper.findPermissionActionBySubjectIdByUrlAction(id, url);
        actionResult.addAll(actionMapper.findRoleActionBySubjectIdByUrlAction(id, url));
        return actionResult;
    }

    //查询
    @Override
    public IPage<JurisdictionVo> selectJurisdictionVoByAllPage(Long page, Long limit) {
        Page<JurisdictionVo> jurisdictionVoPage = new Page<>(page, limit);
        //查询该id有多少角色
        List<Role> roles = subjectMapper.selectSubjectByRole();
        for (Role role : roles) {
            //查询该角色对应的权限
            List<Permission> permissions = roleMapper.selectRoleByPermission(role.getId());
            for (Permission permission : permissions) {
                List<JurisdictionVo> jurisdictionVoList = permissionMapper.selectPermissionByAction(permission.getId());
                for (JurisdictionVo jurisdiction : jurisdictionVoList) {
                    jurisdiction.setRoleName(role.getRoleName());
                    jurisdiction.setRoleDesc(role.getRoleDesc());
                    jurisdictionVoPage.setRecords(jurisdictionVoList);
                }
            }
        }
        return jurisdictionVoPage;
    }

    @Override
    public ResponseVo getAllActionVo() {
        List<ActionTitle> actionList = actionMapper.selectAction();
        log.info(">>>>>>>>>>> ActionList >>>>>" + String.valueOf(actionList.size()));
        List<ActionVo> actionVos = new ArrayList<>();
        for (ActionTitle action : actionList) {
            action.setTitle(action.getActionName());
            //判断一级vo是否存在
            boolean oneExist = false;
            for (ActionVo actionVo : actionVos) {
                if (actionVo.getTitle().equals(action.getModuleName())) {
                    oneExist = true;
                    //判断二级Vo是否存在
                    boolean twoExist = false;
                    for (ActionVo.Two two : actionVo.getChildren()) {
                        if (two.getTitle().equals(action.getSelfParentId())) {
                            twoExist = true;
                            two.addChildren(action);

                        }
                    }
                    if (!twoExist) {
                        ActionVo.Two two = new ActionVo.Two();
                        two.setId((long) 2);
                        two.setTitle(action.getSelfParentId());
                        two.addChildren(action);
                        actionVo.addChildren(two);
                    }
                }
            }
            if (!oneExist) {
                ActionVo actionVo = new ActionVo();
                actionVo.setId((long) 1);
                actionVo.setTitle(action.getModuleName());
                ActionVo.Two two = new ActionVo.Two();
                two.setId((long) 2);
                two.setTitle(action.getSelfParentId());
                two.addChildren(action);
                actionVo.addChildren(two);
                actionVos.add(actionVo);
            }
        }
        return ResponseVo.successWithData(actionVos);
    }

    //新建
    @Override
    public int insertJurisdiction(JurisdictionDto dto) {
        Role role = mapDtoByRole(dto);
        if (roleMapper.insert(role) > 0) {
            Action action = mapDtoByAction(dto);
            if (actionMapper.insert(action) > 0) {
                Permission permission = new Permission();
                if (dto.getType() != null) {
                    permission.setType(dto.getType());
                    if (permissionMapper.insert(permission) > 0) {
                        PermissionActionMapping permissionActionMapping = new PermissionActionMapping();
                        permissionActionMapping.setActionId(action.getId());
                        permissionActionMapping.setPermissionId(permission.getId());
                        RolePermissionMapping rolePermissionMapping = new RolePermissionMapping();
                        rolePermissionMapping.setRoleId(role.getId());
                        rolePermissionMapping.setPermissionId(permission.getId());
                        if (permissionActionMappingMapper.insert(permissionActionMapping) > 0 && rolePermissionMappingMapper.insert(rolePermissionMapping) > 0) {
                            return 1;
                        }
                    }
                }
                return 1;
            }
        }
        return 0;
    }

    //更新
    @Override
    public int updateJurisdiction(JurisdictionDto dto) {
        Role role = mapDtoByRole(dto);
        Action action = mapDtoByAction(dto);
        //根据
        if (actionMapper.updateById(action) > 0) {
            action.setUpdateTime(timeFormat(System.currentTimeMillis()));
            actionMapper.updateById(action);
        }
        if (roleMapper.updateById(role) > 0) {
            role.setUpdateTime(timeFormat(System.currentTimeMillis()));
            roleMapper.updateById(role);
        }
        return 1;
    }


    //dto映射
    private Role mapDtoByRole(JurisdictionDto dto) {
        Role role = new Role();
        if (dto.getRoleName() != null) {
            role.setRoleName(dto.getRoleName());
        }
        if (dto.getActionDesc() != null) {
            role.setRoleDesc(dto.getRoleDesc());
        }
        return role;
    }

    //dto映射
    private Action mapDtoByAction(JurisdictionDto dto) {
        Action action = new Action();
        if (dto.getId() != null) {
            action.setId(dto.getId());
        }
        if (dto.getModuleName() != null) {
            action.setModuleName(dto.getModuleName());
        }
        if (dto.getPatternUrl() != null) {
            action.setPatternUrl(dto.getPatternUrl());
        }
        if (dto.getSelfParentId() != null) {
            action.setSelfParentId(dto.getSelfParentId());
        }
        if (dto.getActionCode() == null) {
            action.setActionCode(String.valueOf(idWorker.nextId()));
        } else {
            action.setActionCode(dto.getActionCode());
        }
        return action;
    }


}
